﻿using Newtonsoft.Json;
using OPCDa;
using OpcSelfHost.basePage;
using OpcSelfHost.printer;
using S7.Net;
using S7PlcHelper;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace OpcSelfHost
{
    public partial class Form1 : Form
    {


        public Form1()
        {
            //执行采集 
            InitializeComponent();

            set_default_value();

           



        }

        //public void Method2(string name, bool isRun)
        //{
        //    while (isRun)
        //    {
        //        Log.LogWrite(DateTime.Now.ToString() + "_", name);
        //        Thread.Sleep(1000);
        //    }

        //}

        /// <summary>
        /// 给form设置默认值
        /// </summary>
        private void set_default_value()
        {
            //窗体设置
            this.StartPosition = FormStartPosition.CenterScreen;
            this.button1.Enabled = true;
            string serverip = "";
            CommonBase.serverip = serverip;

            //设置webapi 
            if (CommonBase.ConfigGetValue("apiport") != "")
            {
                numericUpDown1.Value = int.Parse(CommonBase.ConfigGetValue("apiport"));
            }

            //设置print 
            if (CommonBase.ConfigGetValue("printerip") != "")
            {
                textBox_IPAddress.Text =  CommonBase.ConfigGetValue("printerip");
            }


            //设置ztprint 
            if (CommonBase.ConfigGetValue("ztprinterip") != "")
            {
                textBox2.Text = CommonBase.ConfigGetValue("ztprinterip");
            }





            try
            {
                OPCHelper OPCHelper = new OPCHelper(CommonBase.serverip);
                var return_data = OPCHelper.getOPCservers();
                string jsonStr = JsonConvert.SerializeObject(return_data);
                dynamic jsonParams = JsonConvert.DeserializeObject<dynamic>(jsonStr);
                Dictionary<string, string> kvDictonary = new Dictionary<string, string>();
                for (int i = 0; i < jsonParams.Count; i++)
                {
                    kvDictonary.Add(jsonParams[i].Value, jsonParams[i].Value);
                }
                BindingSource bs = new BindingSource();
                bs.DataSource = kvDictonary;
                comboBox1.DataSource = bs;
                comboBox1.ValueMember = "Key";
                comboBox1.DisplayMember = "Value";

                //设置opc
                if (CommonBase.ConfigGetValue("opcservername") != "")
                {
                    comboBox1.Text = CommonBase.ConfigGetValue("opcservername").ToString();
                }

            }

            

            catch (Exception Ex)
            {
                label12.Text = Ex.Message;
            }


            //初始化plc
            set_plc_lists();
             

            //设置CPU类型
            comboBox2.DataSource = Enum.GetNames(typeof(CpuType));

             

            //自动启动
            if (CommonBase.ConfigGetValue("autorun") != "")
            {
                run_api_server(); //开启api服务
                checkBox1.CheckState = CheckState.Checked;
                //异步调用
                Task run_task = new Task(check_opc_server);
                run_task.Start();
                check_plc_server();
                check_printer_server();
                set_zt_server();
            }




        }

        /// <summary>
        /// 初始化斑马打印服务
        /// </summary>
        private void set_zt_server()
        { 
            ZtAutoPrint h = new ZtAutoPrint();
            h.Ip = textBox2.Text;
            if (h.Check())
            {
                h.Start();
                textBox2.Enabled = false;
            } 
        }

            /// <summary>
            /// 设置plc配置列表
            /// </summary>
            private void set_plc_lists()
        {
            //dataGridView1.Columns[0].FillWeight = 20;
            //dataGridView1.Columns[1].FillWeight = 20;
            //dataGridView1.Columns[2].FillWeight = 20;
            //dataGridView1.Columns[3].FillWeight = 20;
            //plc
            if (CommonBase.ConfigGetValue("plcconfig") != "")
            {
                string plcconfig = CommonBase.ConfigGetValue("plcconfig");

                List<dynamic> jsonParams = JsonConvert.DeserializeObject<List<dynamic>>(plcconfig);
                //添加数据  
                if (jsonParams != null)
                {
                    for (int i = 0; i < jsonParams.Count; i++)
                    {
                        DataGridViewRow dr = new DataGridViewRow();
                        dr.CreateCells(dataGridView1);
                        dr.Cells[0].Value = jsonParams[i].ip;
                        dr.Cells[1].Value = jsonParams[i].cputype;
                        dr.Cells[2].Value = jsonParams[i].rack;
                        dr.Cells[3].Value = jsonParams[i].slot;
                        dataGridView1.Rows.Insert(0, dr);     //插入的数据作为第一行显示
                    }
                }


            }

        }

         


        private void button1_Click(object sender, EventArgs e)
        { 
            label4.Text = "服务开启中……";
            run_api_server();
            check_printer_server();
            check_opc_server();
            check_plc_server(); 
            //初始化斑马
            set_zt_server();


        }

        /// <summary>
        /// 检查打印服务
        /// </summary>
        private void check_printer_server()
        {

            try
            {
                if (SocketClient.Instance.getIsConnected())
                {

                   // SocketClient.Instance.CloseConnection(); 
                   // textBox_IPAddress.Enabled = true; 

                }
                else
                {

                    SocketClient.Instance.setIpAndPort(textBox_IPAddress.Text, 9100);//设置连接的IP
                    if (SocketClient.Instance.ConnetToServices())
                    {
                         
                        textBox_IPAddress.Enabled = false; 

                    }
                    else
                    { 
                        textBox_IPAddress.Enabled = true; 

                    } 
                } 

            }
            catch (Exception ex)
            {
                SetText(ex.Message, false);
            }

              

        }



        /// <summary>
        /// 检查opc服务
        /// </summary>
        private void check_opc_server()
        {

            try
            {
                //非空输入 
               // string servername = comboBox1.Text;
                string servername = GetText();
                string serverip = CommonBase.serverip;
                OPCHelper OPCHelper = new OPCHelper(serverip, servername, 1);
                if (OPCHelper.Connected)
                {
                    CommonBase.servername = servername;
                    SetText("服务连接正常", true);

                }
                else
                {
                    SetText("无法连接到服务器！", false);
                }


            }
            catch (Exception ex)
            {
                SetText(ex.Message, false);
            }

        }

        /// <summary>
        /// 检查plc配置
        /// </summary>
        private bool check_plc_server()
        {

            try
            {
                if (dataGridView1.RowCount == 0)
                {
                    label13.Text = "未配置PLC服务";
                    label13.ForeColor = Color.Red;
                    return false;
                }
                else
                {
                    label13.Text = "连接中……";

                    List<PlcConfig> PlcConfigs = new List<PlcConfig>();

                    for (int i = 0; i < dataGridView1.RowCount; i++)
                    {
                        PlcConfig mPlcConfig = new PlcConfig();
                        mPlcConfig.ip = dataGridView1.Rows[i].Cells[0].Value.ToString();

                        string s_CpuType = dataGridView1.Rows[i].Cells[1].Value.ToString();
                        mPlcConfig.cputype = (CpuType)(Enum.Parse(typeof(CpuType), s_CpuType, true));
                        mPlcConfig.rack = (short)Convert.ToInt16(dataGridView1.Rows[i].Cells[2].Value);
                        mPlcConfig.slot = (short)Convert.ToInt16(dataGridView1.Rows[i].Cells[3].Value);


                        PlcHelper plc = new PlcHelper(mPlcConfig);
                        //尝试连接
                        plc.Open();
                        plc.Close();

                        PlcConfigs.Add(mPlcConfig);

                        label13.Text = "服务连接正常";
                        label13.ForeColor = Color.Green;




                    }

                    CommonBase.mPlcConfigs = PlcConfigs;
                    return true;


                }


            }
            catch (Exception ex)
            {
                label13.Text = ex.Message;
                label13.ForeColor = Color.Red;
                return false;
            }

        }

        


        /// <summary>
        /// 开启api服务
        /// </summary>
        private void run_api_server()
        {

            try
            {
                //非空输入
                var prot = numericUpDown1.Value;
                string StrMachineCode = this.comboBox1.Text;

                string servername = comboBox1.Text;
                string serverip = CommonBase.serverip;

                int port_int = Convert.ToInt32(prot);
                //端口被占用
                if (!PortInUse.PortInUseFun(port_int))
                {
                    WebApi.WebServer.Start(port_int);
                    label4.Text = "服务开启成功";
                    label4.ForeColor = Color.Green;
                    this.button1.Enabled = false;
                    this.button1.BackColor = Color.DarkGray;
                    this.button2.Enabled = true;
                    this.button2.BackColor = Color.RoyalBlue;
                    this.linkLabel1.Visible = true;
                    this.linkLabel2.Visible = true;
                    //设置不可修改
                    this.comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
                    this.numericUpDown1.ReadOnly = true;

                }
                else
                {
                    label4.Text = "端口号被占用";
                    label4.ForeColor = Color.Red;
                }

                ///开启任务  
                CancellationTokenSource tokenSource_plcsend = new CancellationTokenSource();
                CancellationToken token_plcsend = tokenSource_plcsend.Token;

                //定时服务，判断opc是否启动成功 
                Task task = new Task(async () =>
                {
                    //await Task.Delay(SendConfig.read_sec * 1000);
                    while (true)
                    {
                        if (token_plcsend.IsCancellationRequested)
                        {
                            return;
                        }

                        if (CommonBase.servername != null)
                        {
                            return;
                        }

                        check_opc_server();
                        await Task.Delay(3 * 1000);
                    }

                }, token_plcsend);
                task.Start();





            }
            catch (Exception ex)
            {
                label4.Text = ex.Message;
                label4.ForeColor = Color.Red;
            }

        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            String prot = this.numericUpDown1.Value.ToString();
           // string url = "http://127.0.0.1:" + prot + "/views/help.pdf";
            string url = "http://127.0.0.1:" + prot + "/views/points.html";
            System.Diagnostics.Process.Start(url);

        }


        /// <summary>
        /// 保存配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            //先检查服务
            check_opc_server();
            check_plc_server();
            check_printer_server();

            //打印
            CommonBase.ConfigSetValue("printerip", textBox_IPAddress.Text);
            CommonBase.ConfigSetValue("ztprinterip", textBox2.Text);
            

            //opc
            CommonBase.ConfigSetValue("opcservername", comboBox1.Text);

            //webapi
            CommonBase.ConfigSetValue("apiport", numericUpDown1.Value.ToString());
            //plc
            string mPlcConfigsStr = JsonConvert.SerializeObject(CommonBase.mPlcConfigs);
            CommonBase.ConfigSetValue("plcconfig", mPlcConfigsStr);

            //db
            string mDbConfigsStr = JsonConvert.SerializeObject(CommonBase.Dbconfig);
            CommonBase.ConfigSetValue("dbconfig", mDbConfigsStr);



            MessageBox.Show("保存成功!");
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.CheckState == CheckState.Checked)
            {
                CommonBase.ConfigSetValue("autorun", "autorun");
            }
            else
            {
                CommonBase.ConfigSetValue("autorun", "");
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            this.FormClosing += Form1_FormClosing;

        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //注意判断关闭事件Reason来源于窗体按钮，否则用菜单退出时无法退出!
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;    //取消"关闭窗口"事件
                this.WindowState = FormWindowState.Minimized;    //使关闭时窗口向右下角缩小的效果
                notifyIcon1.Visible = true;
                this.Hide();
                return;
            }

        }

        /// <summary>
        /// 委托
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="bool_a"></param>
        public delegate void Lbl_delegate(string msg, bool bool_a);

        /// <summary>
        /// 执行界面
        /// </summary>
        /// <param name="msg"></param>
        private void SetText(string msg, bool bool_a)
        {
            if (label12.InvokeRequired)
            {
                this.Invoke(new Lbl_delegate(SetText), new object[] { msg, bool_a });
            }
            else
            {
                label12.Text = msg;
                if (bool_a)
                {

                    label12.ForeColor = Color.Green;
                }
                else
                {
                    label12.ForeColor = Color.Red;
                }
                Application.DoEvents();
            }
        }

        public delegate string DL_GetText();   //在子线程内 获取 主线程控件的值
        private string GetText()
        {
            try
            {
                if (this.comboBox1.InvokeRequired)
                {

                    DL_GetText stcb = new DL_GetText(GetText);

                    IAsyncResult ia = comboBox1.BeginInvoke(stcb);
                    return (string)comboBox1.EndInvoke(ia);  //这里需要利用EndInvoke来获取返回值


                }
                else
                {
                    return comboBox1.Text;
                }
            }
            catch (Exception Ex)
            {
                return "";
            }
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)    //最小化到系统托盘
            {
                notifyIcon1.Visible = true;    //显示托盘图标
                this.Hide();    //隐藏窗口
            }

        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            notifyIcon1.Visible = false;
            this.Show();
            WindowState = FormWindowState.Normal;
            this.Focus();
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        /// <summary>
        /// 检查配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
             check_opc_server();
             check_printer_server();
            // set_zt_server();  检查服务
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        /// <summary>
        /// 增加plc配置项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {


            try
            {
                //非空输入

                string ip = textBox1.Text;
                string s_CpuType = comboBox2.Text;
                CpuType _CpuType = (CpuType)(Enum.Parse(typeof(CpuType), s_CpuType, true));
                short rack = (short)numericUpDown2.Value;
                short slot = (short)numericUpDown3.Value;


                PlcHelper plc = new PlcHelper(_CpuType, ip, rack, slot);

                label14.Text = "新增中……";
                if (ip == "")
                {
                    label14.Text = "未配置IP";
                    label14.ForeColor = Color.Red;
                }
                else
                {
                    //尝试连接
                    plc.Open();
                    plc.Close();
                    label14.Text = "服务连接正常";
                    label14.ForeColor = Color.Green;

                    //添加数据
                    DataGridViewRow dr = new DataGridViewRow();
                    dr.CreateCells(dataGridView1);
                    dr.Cells[0].Value = ip;
                    dr.Cells[1].Value = s_CpuType;
                    dr.Cells[2].Value = rack;
                    dr.Cells[3].Value = slot;


                    for (int i = 0; i < dataGridView1.RowCount; i++)
                    {
                        if (dataGridView1.Rows[i].Cells[0].Value.ToString() == ip)
                        {
                            dataGridView1.Rows.RemoveAt(i);
                            label14.Text = "已经存在该项";
                            label14.ForeColor = Color.Red;
                        }
                    }
                    dataGridView1.Rows.Insert(0, dr);     //插入的数据作为第一行显示



                    //dgv.Rows.Add(dr);    


                }


            }
            catch (Exception ex)
            {
                label14.Text = ex.Message;
                label14.ForeColor = Color.Red;
            }
        }

        //删除列表一项
        private void button5_Click(object sender, EventArgs e)
        {

            if (dataGridView1.SelectedRows.Count > 0)
            {
                dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);
            }
            else
            {
                label14.Text = "请先选择一行";
                label14.ForeColor = Color.Red;
            }

        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            String prot = this.numericUpDown1.Value.ToString();
            string url = "http://127.0.0.1:" + prot + "/views/print.html";
            System.Diagnostics.Process.Start(url);
        }

        private void label3_Click(object sender, EventArgs e)
        {

        }




        //public delegate void Delegate_Daq(int index, string FieldValue);

        ///// <summary>
        ///// 执行界面
        ///// </summary>
        ///// <param name="msg"></param>
        //private void Update_daqtable(int index, string FieldValue)


        //{
        //   // Thread.Sleep(1000);
        //    if (dataGridView2.InvokeRequired)
        //    {
        //        this.Invoke(new Delegate_Daq(Update_daqtable), new object[] { index, FieldValue });
        //    }
        //    else
        //    {
        //        dataGridView2.Rows[index].Cells["FieldValue"].Value = FieldValue;
        //        Application.DoEvents();
        //    }
        //}







    }
    }


 